package common

import (
	"bufio"
	"errors"
	"fmt"
	"os"
	"os/exec"
	"strings"
	"time"
)

func NetworkSpeedString(size int64, useTime time.Duration) string {
	speed := float64(size) * 8 / useTime.Seconds()
	if speed > 1e6 {
		return fmt.Sprintf("%.1f Mbps", speed/1e6)
	} else if speed > 1e3 {
		return fmt.Sprintf("%.1f Kbps", speed/1e3)
	} else {
		return fmt.Sprintf("%.1f bps", speed/1e6)
	}
}

func SpeedToString(speed int64) string {
	if speed > 1e6 {
		return fmt.Sprintf("%d Mbps", speed/1e6)
	} else if speed > 1e3 {
		return fmt.Sprintf("%d Kbps", speed/1e3)
	} else {
		return fmt.Sprintf("%d bps", speed/1e6)
	}
}
func FileExists(name string) (bool, error) {
	_, err := os.Stat(name)
	if err == nil {
		return true, nil
	}
	if errors.Is(err, os.ErrNotExist) {
		return false, nil
	}
	return false, err
}
func OpenFile(name string) (fp *os.File, size int64, err error) {
	fs, err := os.Stat(name)
	if err != nil {
		return
	}
	size = fs.Size()
	fp, err = os.Open(name)
	return
}
func GetENodeVersionFromFile(nodePath string) string {
	cmd := exec.Command(nodePath, "version")
	data, err := cmd.Output()
	if err != nil {
		return ""
	}
	prefix := "Version:"
	outStrings := strings.Split(string(data), "\n")
	for _, str := range outStrings {
		str = strings.TrimSpace(str)
		str = strings.Trim(str, "\r")
		if len(str) == 0 {
			continue
		}
		if strings.HasPrefix(str, prefix) {
			version := str[len(prefix):]
			fmt.Println("local ", version)
			return strings.TrimSpace(version)
		}
	}
	return ""
}
func IsForbitDir(dir string) bool {
	var prohibit = []string{"/bin", "/sbin", "/dev", "/etc", "/home",
		"/proc", "/sbin", "/sys", "/usr", "/var", "/lib", "/lib64", "/opt"}
	if dir == "/" {
		return true
	}
	if len(dir) > 0 && dir[len(dir)-1] == '/' {
		dir = dir[0 : len(dir)-1]
	}

	for i := range prohibit {
		if strings.HasPrefix(dir, prohibit[i]) {
			return true
		}
	}
	return false
}

func GetP2pUid() (string, error) {
	//todo fix me
	p2pUidfile := "/usr/local/bin/p2puid"

	f, err := os.Open(p2pUidfile)
	if err != nil {
		return "", err
	}
	p2pUid := ""
	buf := bufio.NewReader(f)
	for {
		p2pUid, _ = buf.ReadString('\n')
		p2pUid = strings.TrimSpace(p2pUid)
		p2pUid = strings.Trim(p2pUid, "\r")
		break
	}

	if len(p2pUid) == 0 { //没有值时，继续进行，因为有可能有公网IP或upnp
		err = errors.New("p2puid empty")
		fmt.Println(err)
	}
	return p2pUid, err
}
